#!/usr/bin/env python
# coding=utf-8

import json
from urllib.request import Request,urlopen
from urllib.parse import urlencode
import ssl

ssl._create_default_https_context = ssl._create_unverified_context
url = 'https://fanyi.baidu.com/sug'
# headers = {
#     "user-agent":" Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36"
# }
def translate(kw):
    request = Request(url,data=urlencode({"kw":kw}).encode('utf-8'))
    resp = urlopen(request)
    # assert resp == 200
    json_data = resp.read() # byte类型
    content_charset = resp.getheader("content-type")
    content_charset = "utf-8" if content_charset is None else content_charset.split("=")[-1]
    result = json.loads(json_data.decode('utf-8')) # 反序列化
    # return result.get('data',result)
    return result['data'][0] if result.get('data') else result



if __name__ == '__main__':
    while True:
        kw = input("请输入要查询的数据：")
        if kw:
            print(translate(kw))
            break
        else:
            print("数据不能为空！")
            continue